home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlfaq5.Z / perlfaq5
Encoding:
Text File  |  1998-10-28  |  56.8 KB  |  1,519 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlfaq5 - Files and Formats ($Revision: 1.24    $, $Date:
  10.       1998/07/05 15:07:20 $)
  11.  
  12.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.       This section deals with I/O and the "f" issues: filehandles,
  14.       flushing, formats, and footers.
  15.  
  16.       HHHHoooowwww ddddoooo IIII fffflllluuuusssshhhh////uuuunnnnbbbbuuuuffffffffeeeerrrr aaaannnn oooouuuuttttppppuuuutttt ffffiiiilllleeeehhhhaaaannnnddddlllleeee????     WWWWhhhhyyyy mmmmuuuusssstttt IIII ddddoooo
  17.       tttthhhhiiiissss????
  18.  
  19.       The C    standard I/O library (stdio) normally buffers
  20.       characters sent to devices.  This is done for    efficiency
  21.       reasons, so that there isn't a system    call for each byte.
  22.       Any time you use _p_r_i_n_t() or _w_r_i_t_e() in Perl, you go though
  23.       this buffering.  _s_y_s_w_r_i_t_e() circumvents stdio    and buffering.
  24.  
  25.       In most stdio    implementations, the type of output buffering
  26.       and the size of the buffer varies according to the type of
  27.       device.  Disk    files are block    buffered, often    with a buffer
  28.       size of more than 2k.     Pipes and sockets are often buffered
  29.       with a buffer    size between 1/2 and 2k.  Serial devices (e.g.
  30.       modems, terminals) are normally line-buffered, and stdio
  31.       sends    the entire line    when it    gets the newline.
  32.  
  33.       Perl does not    support    truly unbuffered output    (except
  34.       insofar as you can syswrite(OUT, $char, 1)).    What it    does
  35.       instead support is "command buffering", in which a physical
  36.       write    is performed after every output    command.  This isn't
  37.       as hard on your system as unbuffering, but does get the
  38.       output where you want    it when    you want it.
  39.  
  40.       If you expect    characters to get to your device when you
  41.       print    them there, you'll want    to autoflush its handle.  Use
  42.       _s_e_l_e_c_t() and the $| variable to control autoflushing (see
  43.       the section on $| in the _p_e_r_l_v_a_r manpage and the select
  44.       entry    in the _p_e_r_l_f_u_n_c    manpage):
  45.  
  46.           $old_fh =    select(OUTPUT_HANDLE);
  47.           $| = 1;
  48.           select($old_fh);
  49.  
  50.       Or using the traditional idiom:
  51.  
  52.           select((select(OUTPUT_HANDLE), $|    = 1)[0]);
  53.  
  54.       Or if    don't mind slowly loading several thousand lines of
  55.       module code just because you're afraid of the    $| variable:
  56.  
  57.           use FileHandle;
  58.           open(DEV,    "+</dev/tty");        # ceci n'est pas une pipe
  59.           DEV->autoflush(1);
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  71.  
  72.  
  73.  
  74.       or the newer IO::* modules:
  75.  
  76.           use IO::Handle;
  77.           open(DEV,    ">/dev/printer");   # but is this?
  78.           DEV->autoflush(1);
  79.  
  80.       or even this:
  81.  
  82.           use IO::Socket;            # this one is kinda    a pipe?
  83.           $sock = IO::Socket::INET->new(PeerAddr =>    'www.perl.com',
  84.                         PeerPort =>    'http(80)',
  85.                         Proto    =>    'tcp');
  86.           die "$!" unless $sock;
  87.  
  88.           $sock->autoflush();
  89.           print $sock "GET / HTTP/1.0" . "\015\012"    x 2;
  90.           $document    = join('', <$sock>);
  91.           print "DOC IS: $document\n";
  92.  
  93.       Note the bizarrely hardcoded carriage    return and newline in
  94.       their    octal equivalents.  This is the    ONLY way (currently)
  95.       to assure a proper flush on all platforms, including
  96.       Macintosh.  That the way things work in network programming:
  97.       you really should specify the    exact bit pattern on the
  98.       network line terminator.  In practice, "\n\n"    often works,
  99.       but this is not portable.
  100.  
  101.       See the _p_e_r_l_f_a_q_9 manpage for other examples of fetching URLs
  102.       over the web.
  103.  
  104.       HHHHoooowwww ddddoooo IIII cccchhhhaaaannnnggggeeee oooonnnneeee lllliiiinnnneeee iiiinnnn aaaa    ffffiiiilllleeee////ddddeeeelllleeeetttteeee aaaa lllliiiinnnneeee iiiinnnn aaaa
  105.       ffffiiiilllleeee////iiiinnnnsssseeeerrrrtttt aaaa    lllliiiinnnneeee iiiinnnn    tttthhhheeee mmmmiiiiddddddddlllleeee ooooffff aaaa    ffffiiiilllleeee////aaaappppppppeeeennnndddd ttttoooo tttthhhheeee
  106.       bbbbeeeeggggiiiinnnnnnnniiiinnnngggg ooooffff aaaa ffffiiiilllleeee????
  107.  
  108.       Although humans have an easy time thinking of    a text file as
  109.       being    a sequence of lines that operates much like a stack of
  110.       playing cards    -- or punch cards -- computers usually see the
  111.       text file as a sequence of bytes.  In    general, there's no
  112.       direct way for Perl to seek to a particular line of a    file,
  113.       insert text into a file, or remove text from a file.
  114.  
  115.       (There are exceptions    in special circumstances.  You can add
  116.       or remove at the very    end of the file.  Another is replacing
  117.       a sequence of    bytes with another sequence of the same
  118.       length.  Another is using the    $DB_RECNO array    bindings as
  119.       documented in    the _D_B__F_i_l_e manpage.  Yet another is
  120.       manipulating files with all lines the    same length.)
  121.  
  122.       The general solution is to create a temporary    copy of    the
  123.       text file with the changes you want, then copy that over the
  124.       original.  This assumes no locking.
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  137.  
  138.  
  139.  
  140.           $old = $file;
  141.           $new = "$file.tmp.$$";
  142.           $bak = "$file.bak";
  143.  
  144.           open(OLD,    "< $old")      or die "can't    open $old: $!";
  145.           open(NEW,    "> $new")      or die "can't    open $new: $!";
  146.  
  147.           #    Correct    typos, preserving case
  148.           while (<OLD>) {
  149.           s/\b(p)earl\b/${1}erl/i;
  150.           (print NEW $_)      or die "can't    write to $new: $!";
  151.           }
  152.  
  153.           close(OLD)          or die "can't    close $old: $!";
  154.           close(NEW)          or die "can't    close $new: $!";
  155.  
  156.           rename($old, $bak)      or die "can't    rename $old to $bak: $!";
  157.           rename($new, $old)      or die "can't    rename $new to $old: $!";
  158.  
  159.       Perl can do this sort    of thing for you automatically with
  160.       the -i command-line switch or    the closely-related $^I
  161.       variable (see    the _p_e_r_l_r_u_n manpage for    more details).    Note
  162.       that -i may require a    suffix on some non-Unix    systems; see
  163.       the platform-specific    documentation that came    with your
  164.       port.
  165.  
  166.           #    Renumber a series of tests from    the command line
  167.           perl -pi -e 's/(^\s+test\s+)\d+/ $1 . ++$count /e' t/op/taint.t
  168.  
  169.           #    form a script
  170.           local($^I, @ARGV)    = ('.bak', glob("*.c"));
  171.           while (<>) {
  172.           if ($. == 1) {
  173.               print "This line should appear at    the top    of each    file\n";
  174.           }
  175.           s/\b(p)earl\b/${1}erl/i;      # Correct typos, preserving case
  176.           print;
  177.           close    ARGV if    eof;          # Reset $.
  178.           }
  179.  
  180.       If you need to seek to an arbitrary line of a    file that
  181.       changes infrequently,    you could build    up an index of byte
  182.       positions of where the line ends are in the file.  If    the
  183.       file is large, an index of every tenth or hundredth line end
  184.       would    allow you to seek and read fairly efficiently.    If the
  185.       file is sorted, try the look.pl library (part    of the
  186.       standard perl    distribution).
  187.  
  188.       In the unique    case of    deleting lines at the end of a file,
  189.       you can use _t_e_l_l() and _t_r_u_n_c_a_t_e().  The following code
  190.       snippet deletes the last line    of a file without making a
  191.       copy or reading the whole file into memory:
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  203.  
  204.  
  205.  
  206.           open (FH, "+<    $file");
  207.           while    ( <FH> ) { $addr = tell(FH) unless eof(FH) }
  208.           truncate(FH, $addr);
  209.  
  210.       Error    checking is left as an exercise    for the    reader.
  211.  
  212.       HHHHoooowwww ddddoooo IIII ccccoooouuuunnnntttt tttthhhheeee nnnnuuuummmmbbbbeeeerrrr ooooffff lllliiiinnnneeeessss iiiinnnn    aaaa ffffiiiilllleeee????
  213.  
  214.       One fairly efficient way is to count newlines    in the file.
  215.       The following    program    uses a feature of tr///, as documented
  216.       in the _p_e_r_l_o_p    manpage.  If your text file doesn't end    with a
  217.       newline, then    it's not really    a proper text file, so this
  218.       may report one fewer line than you expect.
  219.  
  220.           $lines = 0;
  221.           open(FILE, $filename) or die "Can't open `$filename': $!";
  222.           while (sysread FILE, $buffer, 4096) {
  223.           $lines += ($buffer =~    tr/\n//);
  224.           }
  225.           close FILE;
  226.  
  227.       This assumes no funny    games with newline translations.
  228.  
  229.       HHHHoooowwww ddddoooo IIII mmmmaaaakkkkeeee    aaaa tttteeeemmmmppppoooorrrraaaarrrryyyy ffffiiiilllleeee nnnnaaaammmmeeee????
  230.  
  231.       Use the new_tmpfile class method from    the IO::File module to
  232.       get a    filehandle opened for reading and writing.  Use    this
  233.       if you don't need to know the    file's name.
  234.  
  235.           use IO::File;
  236.           $fh = IO::File->new_tmpfile()
  237.               or die "Unable to    make new temporary file: $!";
  238.  
  239.       Or you can use the tmpnam function from the POSIX module to
  240.       get a    filename that you then open yourself.  Use this    if you
  241.       do need to know the file's name.
  242.  
  243.           use Fcntl;
  244.           use POSIX    qw(tmpnam);
  245.  
  246.           #    try new    temporary filenames until we get one that didn't already
  247.           #    exist;    the check should be unnecessary, but you can't be too careful
  248.           do { $name = tmpnam() }
  249.           until    sysopen(FH, $name, O_RDWR|O_CREAT|O_EXCL);
  250.  
  251.           #    install    atexit-style handler so    that when we exit or die,
  252.           #    we automatically delete    this temporary file
  253.           END { unlink($name) or die "Couldn't unlink $name    : $!" }
  254.  
  255.           #    now go on to use the file ...
  256.  
  257.       If you're committed to doing this by hand, use the process
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  269.  
  270.  
  271.  
  272.       ID and/or the    current    time-value.  If    you need to have many
  273.       temporary files in one process, use a    counter:
  274.  
  275.           BEGIN {
  276.           use Fcntl;
  277.           my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMP}    || $ENV{TEMP};
  278.           my $base_name    = sprintf("%s/%d-%d-0000", $temp_dir, $$, time());
  279.           sub temp_file    {
  280.               local *FH;
  281.               my $count    = 0;
  282.               until (defined(fileno(FH)) || $count++ > 100) {
  283.               $base_name =~    s/-(\d+)$/"-" .    (1 + $1)/e;
  284.               sysopen(FH, $base_name, O_WRONLY|O_EXCL|O_CREAT);
  285.               }
  286.               if (defined(fileno(FH))
  287.               return (*FH, $base_name);
  288.               }    else {
  289.               return ();
  290.               }
  291.           }
  292.           }
  293.  
  294.  
  295.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaannnniiiippppuuuullllaaaatttteeee ffffiiiixxxxeeeedddd----rrrreeeeccccoooorrrrdddd----lllleeeennnnggggtttthhhh ffffiiiilllleeeessss????
  296.  
  297.       The most efficient way is using _p_a_c_k() and _u_n_p_a_c_k().    This
  298.       is faster than using _s_u_b_s_t_r()    when take many,    many strings.
  299.       It is    slower for just    a few.
  300.  
  301.       Here is a sample chunk of code to break up and put back
  302.       together again some fixed-format input lines,    in this    case
  303.       from the output of a normal, Berkeley-style ps:
  304.  
  305.           #    sample input line:
  306.           #      15158    p5  T       0:00    perl /home/tchrist/scripts/now-what
  307.           $PS_T = 'A6 A4 A7    A5 A*';
  308.           open(PS, "ps|");
  309.           print scalar <PS>;
  310.           while (<PS>) {
  311.           ($pid, $tt, $stat, $time, $command) =    unpack($PS_T, $_);
  312.           for $var (qw!pid tt stat time    command!) {
  313.               print "$var: <$$var>\n";
  314.           }
  315.           print    'line=', pack($PS_T, $pid, $tt,    $stat, $time, $command),
  316.               "\n";
  317.           }
  318.  
  319.       We've    used $$var in a    way that forbidden by use strict
  320.       'refs'.  That    is, we've promoted a string to a scalar
  321.       variable reference using symbolic references.     This is ok in
  322.       small    programs, but doesn't scale well.   It also only works
  323.       on global variables, not lexicals.
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  335.  
  336.  
  337.  
  338.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee aaaa ffffiiiilllleeeehhhhaaaannnnddddlllleeee llllooooccccaaaallll ttttoooo aaaa ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee????  HHHHoooowwww ddddoooo IIII
  339.       ppppaaaassssssss ffffiiiilllleeeehhhhaaaannnnddddlllleeeessss bbbbeeeettttwwwweeeeeeeennnn ssssuuuubbbbrrrroooouuuuttttiiiinnnneeeessss????     HHHHoooowwww ddddoooo    IIII mmmmaaaakkkkeeee aaaannnn
  340.       aaaarrrrrrrraaaayyyy    ooooffff ffffiiiilllleeeehhhhaaaannnnddddlllleeeessss????
  341.  
  342.       The fastest, simplest, and most direct way is    to localize
  343.       the typeglob of the filehandle in question:
  344.  
  345.           local *TmpHandle;
  346.  
  347.       Typeglobs are    fast (especially compared with the
  348.       alternatives)    and reasonably easy to use, but    they also have
  349.       one subtle drawback.    If you had, for    example, a function
  350.       named    _T_m_p_H_a_n_d_l_e(), or    a variable named %TmpHandle, you just
  351.       hid it from yourself.
  352.  
  353.           sub findme {
  354.           local    *HostFile;
  355.           open(HostFile, "</etc/hosts")    or die "no /etc/hosts: $!";
  356.           local    $_;          # <- VERY IMPORTANT
  357.           while    (<HostFile>) {
  358.               print if /\b127\.(0\.0\.)?1\b/;
  359.           }
  360.           # *HostFile automatically closes/disappears here
  361.           }
  362.  
  363.       Here's how to    use this in a loop to open and store a bunch
  364.       of filehandles.  We'll use as    values of the hash an ordered
  365.       pair to make it easy to sort the hash    in insertion order.
  366.  
  367.           @names = qw(motd termcap passwd hosts);
  368.           my $i = 0;
  369.           foreach $filename    (@names) {
  370.           local    *FH;
  371.           open(FH, "/etc/$filename") ||    die "$filename:    $!";
  372.           $file{$filename} = [ $i++, *FH ];
  373.           }
  374.  
  375.           #    Using the filehandles in the array
  376.           foreach $name (sort { $file{$a}[0] <=> $file{$b}[0] } keys %file)    {
  377.           my $fh = $file{$name}[1];
  378.           my $line = <$fh>;
  379.           print    "$name $. $line";
  380.           }
  381.  
  382.       For passing filehandles to functions,    the easiest way    is to
  383.       prefer them with a star, as in _f_u_n_c(*STDIN).    See the
  384.       section on _P_a_s_s_i_n_g _F_i_l_e_h_a_n_d_l_e_s in the    _p_e_r_l_f_a_q_7 manpage for
  385.       details.
  386.  
  387.       If you want to create    many, anonymous    handles, you should
  388.       check    out the    Symbol,    FileHandle, or IO::Handle (etc.)
  389.       modules.  Here's the equivalent code with Symbol::gensym,
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  401.  
  402.  
  403.  
  404.       which    is reasonably light-weight:
  405.  
  406.           foreach $filename    (@names) {
  407.           use Symbol;
  408.           my $fh = gensym();
  409.           open($fh, "/etc/$filename") || die "open /etc/$filename: $!";
  410.           $file{$filename} = [ $i++, $fh ];
  411.           }
  412.  
  413.       Or here using    the semi-object-oriented FileHandle, which
  414.       certainly isn't light-weight:
  415.  
  416.           use FileHandle;
  417.  
  418.           foreach $filename    (@names) {
  419.           my $fh = FileHandle->new("/etc/$filename") or    die "$filename:    $!";
  420.           $file{$filename} = [ $i++, $fh ];
  421.           }
  422.  
  423.       Please understand that whether the filehandle    happens    to be
  424.       a (probably localized) typeglob or an    anonymous handle from
  425.       one of the modules, in no way    affects    the bizarre rules for
  426.       managing indirect handles.  See the next question.
  427.  
  428.       HHHHoooowwww ccccaaaannnn IIII uuuusssseeee    aaaa ffffiiiilllleeeehhhhaaaannnnddddlllleeee iiiinnnnddddiiiirrrreeeeccccttttllllyyyy????
  429.  
  430.       An indirect filehandle is using something other than a
  431.       symbol in a place that a filehandle is expected.  Here are
  432.       ways to get those:
  433.  
  434.           $fh =   SOME_FH;         # bareword    is strict-subs hostile
  435.           $fh =  "SOME_FH";         # strict-refs hostile; same package only
  436.           $fh =  *SOME_FH;         # typeglob
  437.           $fh = \*SOME_FH;         # ref to typeglob (bless-able)
  438.           $fh =  *SOME_FH{IO};   # blessed IO::Handle from *SOME_FH    typeglob
  439.  
  440.       Or to    use the    new method from    the FileHandle or IO modules
  441.       to create an anonymous filehandle, store that    in a scalar
  442.       variable, and    use it as though it were a normal filehandle.
  443.  
  444.           use FileHandle;
  445.           $fh = FileHandle->new();
  446.  
  447.           use IO::Handle;              # 5.004 or higher
  448.           $fh = IO::Handle->new();
  449.  
  450.       Then use any of those    as you would a normal filehandle.
  451.       Anywhere that    Perl is    expecting a filehandle,    an indirect
  452.       filehandle may be used instead. An indirect filehandle is
  453.       just a scalar    variable that contains a filehandle.
  454.       Functions like print,    open, seek, or the functions or    the
  455.       <FH> diamond operator    will accept either a read filehandle
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  467.  
  468.  
  469.  
  470.       or a scalar variable containing one:
  471.  
  472.           ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
  473.           print $ofh "Type it: ";
  474.           $got = <$ifh>
  475.           print $efh "What was that: $got";
  476.  
  477.       Of you're passing a filehandle to a function,    you can    write
  478.       the function in two ways:
  479.  
  480.           sub accept_fh {
  481.           my $fh = shift;
  482.           print    $fh "Sending to    indirect filehandle\n";
  483.           }
  484.  
  485.       Or it    can localize a typeglob    and use    the filehandle
  486.       directly:
  487.  
  488.           sub accept_fh {
  489.           local    *FH = shift;
  490.           print     FH "Sending to    localized filehandle\n";
  491.           }
  492.  
  493.       Both styles work with    either objects or typeglobs of real
  494.       filehandles.    (They might also work with strings under some
  495.       circumstances, but this is risky.)
  496.  
  497.           accept_fh(*STDOUT);
  498.           accept_fh($handle);
  499.  
  500.       In the examples above, we assigned the filehandle to a
  501.       scalar variable before using it.  That is because only
  502.       simple scalar    variables, not expressions or subscripts into
  503.       hashes or arrays, can    be used    with built-ins like print,
  504.       printf, or the diamond operator.  These are illegal and
  505.       won't    even compile:
  506.  
  507.           @fd = (*STDIN, *STDOUT, *STDERR);
  508.           print $fd[1] "Type it: ";                  # WRONG
  509.           $got = <$fd[0]>                      # WRONG
  510.           print $fd[2] "What was that: $got";          # WRONG
  511.  
  512.       With print and printf, you get around    this by    using a    block
  513.       and an expression where you would place the filehandle:
  514.  
  515.           print  { $fd[1] }    "funny stuff\n";
  516.           printf { $fd[1] }    "Pity the poor %x.\n", 3_735_928_559;
  517.           #    Pity the poor deadbeef.
  518.  
  519.       That block is    a proper block like any    other, so you can put
  520.       more complicated code    there.    This sends the message out to
  521.       one of two places:
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  533.  
  534.  
  535.  
  536.           $ok = -x "/bin/cat";
  537.           print { $ok ? $fd[1] : $fd[2] } "cat stat    $ok\n";
  538.           print { $fd[ 1+ ($ok || 0) ]  } "cat stat    $ok\n";
  539.  
  540.       This approach    of treating print and printf like object
  541.       methods calls    doesn't    work for the diamond operator.    That's
  542.       because it's a real operator,    not just a function with a
  543.       comma-less argument.    Assuming you've    been storing typeglobs
  544.       in your structure as we did above, you can use the built-in
  545.       function named readline to reads a record just as <> does.
  546.       Given    the initialization shown above for @fd,    this would
  547.       work,    but only because _r_e_a_d_l_i_n_e() require a typeglob.     It
  548.       doesn't work with objects or strings,    which might be a bug
  549.       we haven't fixed yet.
  550.  
  551.           $got = readline($fd[0]);
  552.  
  553.       Let it be noted that the flakiness of    indirect filehandles
  554.       is not related to whether they're strings, typeglobs,
  555.       objects, or anything else.  It's the syntax of the
  556.       fundamental operators.  Playing the object game doesn't help
  557.       you at all here.
  558.  
  559.       HHHHoooowwww ccccaaaannnn IIII sssseeeetttt    uuuupppp aaaa ffffooooooootttteeeerrrr ffffoooorrrrmmmmaaaatttt ttttoooo bbbbeeee uuuusssseeeedddd wwwwiiiitttthhhh _w_r_i_t_e()?
  560.  
  561.       There's no builtin way to do this, but the _p_e_r_l_f_o_r_m manpage
  562.       has a    couple of techniques to    make it    possible for the
  563.       intrepid hacker.
  564.  
  565.       HHHHoooowwww ccccaaaannnn IIII _w_r_i_t_e() into a string?
  566.  
  567.       See the _p_e_r_l_f_o_r_m manpage for an _s_w_r_i_t_e() function.
  568.  
  569.       HHHHoooowwww ccccaaaannnn IIII oooouuuuttttppppuuuutttt mmmmyyyy nnnnuuuummmmbbbbeeeerrrrssss wwwwiiiitttthhhh ccccoooommmmmmmmaaaassss aaaaddddddddeeeedddd????
  570.  
  571.       This one will    do it for you:
  572.  
  573.           sub commify {
  574.           local    $_  = shift;
  575.           1 while s/^(-?\d+)(\d{3})/$1,$2/;
  576.           return $_;
  577.           }
  578.  
  579.           $n = 23659019423.2331;
  580.           print "GOT: ", commify($n), "\n";
  581.  
  582.           GOT: 23,659,019,423.2331
  583.  
  584.       You can't just:
  585.  
  586.           s/^(-?\d+)(\d{3})/$1,$2/g;
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  599.  
  600.  
  601.  
  602.       because you have to put the comma in and then    recalculate
  603.       your position.
  604.  
  605.       Alternatively, this commifies    all numbers in a line
  606.       regardless of    whether    they have decimal portions, are
  607.       preceded by +    or -, or whatever:
  608.  
  609.           #    from Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
  610.           sub commify {
  611.          my $input = shift;
  612.           $input = reverse $input;
  613.           $input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
  614.           return reverse $input;
  615.           }
  616.  
  617.  
  618.       HHHHoooowwww ccccaaaannnn IIII ttttrrrraaaannnnssssllllaaaatttteeee ttttiiiillllddddeeeessss ((((~~~~)))) iiiinnnn aaaa ffffiiiilllleeeennnnaaaammmmeeee????
  619.  
  620.       Use the <> (_g_l_o_b()) operator,    documented in the _p_e_r_l_f_u_n_c
  621.       manpage.  This requires that you have    a shell    installed that
  622.       groks    tildes,    meaning    csh or tcsh or (some versions of) ksh,
  623.       and thus may have portability    problems.  The Glob::KGlob
  624.       module (available from CPAN) gives more portable glob
  625.       functionality.
  626.  
  627.       Within Perl, you may use this    directly:
  628.  
  629.           $filename =~ s{
  630.             ^ ~            # find a leading tilde
  631.             (            # save this    in $1
  632.             [^/]        # a    non-slash character
  633.                   *        # repeated 0 or more times (0 means    me)
  634.             )
  635.           }{
  636.             $1
  637.             ? (getpwnam($1))[7]
  638.             : ( $ENV{HOME} || $ENV{LOGDIR} )
  639.           }ex;
  640.  
  641.  
  642.       HHHHoooowwww ccccoooommmmeeee wwwwhhhheeeennnn    IIII ooooppppeeeennnn aaaa ffffiiiilllleeee rrrreeeeaaaadddd----wwwwrrrriiiitttteeee iiiitttt wwwwiiiippppeeeessss iiiitttt oooouuuutttt????
  643.  
  644.       Because you're using something like this, which truncates
  645.       the file and _t_h_e_n gives you read-write access:
  646.  
  647.           open(FH, "+> /path/name");      # WRONG (almost always)
  648.  
  649.       Whoops.  You should instead use this,    which will fail    if the
  650.       file doesn't exist.  Using ">" always    clobbers or creates.
  651.       Using    "<" never does either.    The "+"    doesn't    change this.
  652.  
  653.       Here are examples of many kinds of file opens.  Those    using
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  665.  
  666.  
  667.  
  668.       _s_y_s_o_p_e_n() all    assume
  669.  
  670.           use Fcntl;
  671.  
  672.       To open file for reading:
  673.  
  674.           open(FH, "< $path")                  || die $!;
  675.           sysopen(FH, $path, O_RDONLY)              || die $!;
  676.  
  677.       To open file for writing, create new file if needed or else
  678.       truncate old file:
  679.  
  680.           open(FH, "> $path") || die $!;
  681.           sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT)      || die $!;
  682.           sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666)  || die $!;
  683.  
  684.       To open file for writing, create new file, file must not
  685.       exist:
  686.  
  687.           sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT)      || die $!;
  688.           sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0666)      || die $!;
  689.  
  690.       To open file for appending, create if    necessary:
  691.  
  692.           open(FH, ">> $path") || die $!;
  693.           sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT)      || die $!;
  694.           sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0666) || die $!;
  695.  
  696.       To open file for appending, file must    exist:
  697.  
  698.           sysopen(FH, $path, O_WRONLY|O_APPEND)          || die $!;
  699.  
  700.       To open file for update, file    must exist:
  701.  
  702.           open(FH, "+< $path")                  || die $!;
  703.           sysopen(FH, $path, O_RDWR)              || die $!;
  704.  
  705.       To open file for update, create file if necessary:
  706.  
  707.           sysopen(FH, $path, O_RDWR|O_CREAT)          || die $!;
  708.           sysopen(FH, $path, O_RDWR|O_CREAT, 0666)          || die $!;
  709.  
  710.       To open file for update, file    must not exist:
  711.  
  712.           sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT)          || die $!;
  713.           sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT,    0666)      || die $!;
  714.  
  715.       To open a file without blocking, creating if necessary:
  716.  
  717.           sysopen(FH, "/tmp/somefile", O_WRONLY|O_NDELAY|O_CREAT)
  718.               or die "can't open /tmp/somefile:    $!":
  719.  
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  731.  
  732.  
  733.  
  734.       Be warned that neither creation nor deletion of files    is
  735.       guaranteed to    be an atomic operation over NFS.  That is, two
  736.       processes might both successful create or unlink the same
  737.       file!     Therefore O_EXCL isn't    so exclusive as    you might
  738.       wish.
  739.  
  740.       WWWWhhhhyyyy ddddoooo IIII ssssoooommmmeeeettttiiiimmmmeeeessss ggggeeeetttt aaaannnn """"AAAArrrrgggguuuummmmeeeennnntttt lllliiiisssstttt ttttoooooooo lllloooonnnngggg"""" wwwwhhhheeeennnn IIII
  741.       uuuusssseeee <<<<****>>>>????
  742.  
  743.       The <> operator performs a globbing operation    (see above).
  744.       By default _g_l_o_b() forks _c_s_h(1) to do the actual glob
  745.       expansion, but csh can't handle more than 127    items and so
  746.       gives    the error message Argument list    too long.  People who
  747.       installed tcsh as csh    won't have this    problem, but their
  748.       users    may be surprised by it.
  749.  
  750.       To get around    this, either do    the glob yourself with
  751.       Dirhandles and patterns, or use a module like    Glob::KGlob,
  752.       one that doesn't use the shell to do globbing.
  753.  
  754.       IIIIssss tttthhhheeeerrrreeee aaaa lllleeeeaaaakkkk////bbbbuuuugggg iiiinnnn _g_l_o_b()?
  755.  
  756.       Due to the current implementation on some operating systems,
  757.       when you use the _g_l_o_b() function or its angle-bracket    alias
  758.       in a scalar context, you may cause a leak and/or
  759.       unpredictable    behavior.  It's    best therefore to use _g_l_o_b()
  760.       only in list context.
  761.  
  762.       HHHHoooowwww ccccaaaannnn IIII ooooppppeeeennnn aaaa ffffiiiilllleeee    wwwwiiiitttthhhh aaaa lllleeeeaaaaddddiiiinnnngggg """">>>>"""" oooorrrr ttttrrrraaaaiiiilllliiiinnnngggg bbbbllllaaaannnnkkkkssss????
  763.  
  764.       Normally perl    ignores    trailing blanks    in filenames, and
  765.       interprets certain leading characters    (or a trailing "|") to
  766.       mean something special.  To avoid this, you might want to
  767.       use a    routine    like this.  It makes incomplete    pathnames into
  768.       explicit relative ones, and tacks a trailing null byte on
  769.       the name to make perl    leave it alone:
  770.  
  771.           sub safe_filename    {
  772.           local    $_  = shift;
  773.           return m#^/#
  774.               ? "$_\0"
  775.               : "./$_\0";
  776.           }
  777.  
  778.           $fn = safe_filename("<<<something    really wicked    ");
  779.           open(FH, "> $fn")    or "couldn't open $fn: $!";
  780.  
  781.       You could also use the _s_y_s_o_p_e_n() function (see the sysopen
  782.       entry    in the _p_e_r_l_f_u_n_c    manpage).
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  797.  
  798.  
  799.  
  800.       HHHHoooowwww ccccaaaannnn IIII rrrreeeelllliiiiaaaabbbbllllyyyy rrrreeeennnnaaaammmmeeee aaaa ffffiiiilllleeee????
  801.  
  802.       Well,    usually    you just use Perl's _r_e_n_a_m_e() function.    But
  803.       that may not work everywhere,    in particular, renaming    files
  804.       across file systems.    If your    operating system supports a
  805.       _m_v(1)    program    or its moral equivalent, this works:
  806.  
  807.           rename($old, $new) or system("mv", $old, $new);
  808.  
  809.       It may be more compelling to use the File::Copy module
  810.       instead.  You    just copy to the new file to the new name
  811.       (checking return values), then delete    the old    one.  This
  812.       isn't    really the same    semantics as a real _r_e_n_a_m_e(), though,
  813.       which    preserves metainformation like permissions,
  814.       timestamps, inode info, etc.
  815.  
  816.       The newer version of File::Copy export a _m_o_v_e() function.
  817.  
  818.       HHHHoooowwww ccccaaaannnn IIII lllloooocccckkkk aaaa ffffiiiilllleeee????
  819.  
  820.       Perl's builtin _f_l_o_c_k() function (see the _p_e_r_l_f_u_n_c manpage
  821.       for details) will call _f_l_o_c_k(2) if that exists, _f_c_n_t_l(2) if
  822.       it doesn't (on perl version 5.004 and    later),    and _l_o_c_k_f(3)
  823.       if neither of    the two    previous system    calls exists.  On some
  824.       systems, it may even use a different form of native locking.
  825.       Here are some    gotchas    with Perl's _f_l_o_c_k():
  826.  
  827.       1   Produces a fatal error if    none of    the three system calls
  828.           (or their    close equivalent) exists.
  829.  
  830.       2   _l_o_c_k_f(3) does not    provide    shared locking,    and requires
  831.           that the filehandle be open for writing (or appending,
  832.           or read/writing).
  833.  
  834.       3   Some versions of _f_l_o_c_k() can't lock files    over a network
  835.           (e.g. on NFS file    systems), so you'd need    to force the
  836.           use of _f_c_n_t_l(2) when you build Perl.  See    the flock
  837.           entry of the _p_e_r_l_f_u_n_c manpage, and the _I_N_S_T_A_L_L file in
  838.           the source distribution for information on building Perl
  839.           to do this.
  840.  
  841.       WWWWhhhhaaaatttt ccccaaaannnn''''tttt IIII jjjjuuuusssstttt _o_p_e_n(FH, ">file.lock")?
  842.  
  843.       A common bit of code NNNNOOOOTTTT TTTTOOOO UUUUSSSSEEEE is this:
  844.  
  845.           sleep(3) while -e    "file.lock";      # PLEASE DO NOT USE
  846.           open(LCK,    "> file.lock");          # THIS BROKEN    CODE
  847.  
  848.       This is a classic race condition: you    take two steps to do
  849.       something which must be done in one.    That's why computer
  850.       hardware provides an atomic test-and-set instruction.      In
  851.       theory, this "ought" to work:
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  863.  
  864.  
  865.  
  866.           sysopen(FH, "file.lock", O_WRONLY|O_EXCL|O_CREAT)
  867.               or die "can't    open  file.lock: $!":
  868.  
  869.       except that lamentably, file creation    (and deletion) is not
  870.       atomic over NFS, so this won't work (at least, not every
  871.       time)    over the net.  Various schemes involving involving
  872.       _l_i_n_k() have been suggested, but these    tend to    involve    busy-
  873.       wait,    which is also subdesirable.
  874.  
  875.       IIII ssssttttiiiillllllll ddddoooonnnn''''tttt    ggggeeeetttt lllloooocccckkkkiiiinnnngggg....  IIII    jjjjuuuusssstttt wwwwaaaannnntttt ttttoooo iiiinnnnccccrrrreeeemmmmeeeennnntttt tttthhhheeee
  876.       nnnnuuuummmmbbbbeeeerrrr iiiinnnn tttthhhheeee    ffffiiiilllleeee....  HHHHoooowwww ccccaaaannnn IIII ddddoooo tttthhhhiiiissss????
  877.  
  878.       Didn't anyone    ever tell you web-page hit counters were
  879.       useless?  They don't count number of hits, they're a waste
  880.       of time, and they serve only to stroke the writer's vanity.
  881.       Better to pick a random number.  It's    more realistic.
  882.  
  883.       Anyway, this is what you can do if you can't help yourself.
  884.  
  885.           use Fcntl;
  886.           sysopen(FH, "numfile", O_RDWR|O_CREAT)       or die "can't open numfile: $!";
  887.           flock(FH,    2)                   or die "can't flock numfile:    $!";
  888.           $num = <FH> || 0;
  889.           seek(FH, 0, 0)                   or die "can't rewind    numfile: $!";
  890.           truncate(FH, 0)                   or die "can't truncate numfile: $!";
  891.           (print FH    $num+1,    "\n")               or die "can't write numfile:    $!";
  892.           #    DO NOT UNLOCK THIS UNTIL YOU CLOSE
  893.           close FH                       or die "can't close numfile:    $!";
  894.  
  895.       Here's a much    better web-page    hit counter:
  896.  
  897.           $hits = int( (time() - 850_000_000) / rand(1_000)    );
  898.  
  899.       If the count doesn't impress your friends, then the code
  900.       might.  :-)
  901.  
  902.       HHHHoooowwww ddddoooo IIII rrrraaaannnnddddoooommmmllllyyyy uuuuppppddddaaaatttteeee aaaa bbbbiiiinnnnaaaarrrryyyy ffffiiiilllleeee????
  903.  
  904.       If you're just trying    to patch a binary, in many cases
  905.       something as simple as this works:
  906.  
  907.           perl -i -pe 's{window manager}{window mangler}g' /usr/bin/emacs
  908.  
  909.       However, if you have fixed sized records, then you might do
  910.       something more like this:
  911.  
  912.  
  913.  
  914.  
  915.  
  916.  
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  929.  
  930.  
  931.  
  932.           $RECSIZE = 220; #    size of    record,    in bytes
  933.           $recno   = 37;  #    which record to    update
  934.           open(FH, "+<somewhere") || die "can't update somewhere: $!";
  935.           seek(FH, $recno *    $RECSIZE, 0);
  936.           read(FH, $record,    $RECSIZE) == $RECSIZE || die "can't read record    $recno:    $!";
  937.           #    munge the record
  938.           seek(FH, $recno *    $RECSIZE, 0);
  939.           print FH $record;
  940.           close FH;
  941.  
  942.       Locking and error checking are left as an exercise for the
  943.       reader.  Don't forget    them, or you'll    be quite sorry.
  944.  
  945.       HHHHoooowwww ddddoooo IIII ggggeeeetttt aaaa ffffiiiilllleeee''''ssss    ttttiiiimmmmeeeessssttttaaaammmmpppp iiiinnnn ppppeeeerrrrllll????
  946.  
  947.       If you want to retrieve the time at which the    file was last
  948.       read,    written, or had    its meta-data (owner, etc) changed,
  949.       you use the ----MMMM, ----AAAA, or ----CCCC filetest operations    as documented
  950.       in the _p_e_r_l_f_u_n_c manpage.  These retrieve the age of the file
  951.       (measured against the    start-time of your program) in days as
  952.       a floating point number.  To retrieve    the "raw" time in
  953.       seconds since    the epoch, you would call the stat function,
  954.       then use _l_o_c_a_l_t_i_m_e(),    _g_m_t_i_m_e(), or _P_O_S_I_X::_s_t_r_f_t_i_m_e() to
  955.       convert this into human-readable form.
  956.  
  957.       Here's an example:
  958.  
  959.           $write_secs = (stat($file))[9];
  960.           printf "file %s updated at %s\n",    $file,
  961.           scalar localtime($write_secs);
  962.  
  963.       If you prefer    something more legible,    use the    File::stat
  964.       module (part of the standard distribution in version 5.004
  965.       and later):
  966.  
  967.           use File::stat;
  968.           use Time::localtime;
  969.           $date_string = ctime(stat($file)->mtime);
  970.           print "file $file    updated    at $date_string\n";
  971.  
  972.       Error    checking is left as an exercise    for the    reader.
  973.  
  974.       HHHHoooowwww ddddoooo IIII sssseeeetttt aaaa ffffiiiilllleeee''''ssss    ttttiiiimmmmeeeessssttttaaaammmmpppp iiiinnnn ppppeeeerrrrllll????
  975.  
  976.       You use the _u_t_i_m_e() function documented in the utime entry
  977.       in the _p_e_r_l_f_u_n_c manpage.  By way of example, here's a    little
  978.       program that copies the read and write times from its    first
  979.       argument to all the rest of them.
  980.  
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  995.  
  996.  
  997.  
  998.           if (@ARGV    < 2) {
  999.           die "usage: cptimes timestamp_file other_files ...\n";
  1000.           }
  1001.           $timestamp = shift;
  1002.           ($atime, $mtime) = (stat($timestamp))[8,9];
  1003.           utime $atime, $mtime, @ARGV;
  1004.  
  1005.       Error    checking is left as an exercise    for the    reader.
  1006.  
  1007.       Note that _u_t_i_m_e() currently doesn't work correctly with
  1008.       Win95/NT ports.  A bug has been reported.  Check it
  1009.       carefully before using it on those platforms.
  1010.  
  1011.       HHHHoooowwww ddddoooo IIII pppprrrriiiinnnntttt ttttoooo mmmmoooorrrreeee tttthhhhaaaannnn oooonnnneeee ffffiiiilllleeee aaaatttt oooonnnncccceeee????
  1012.  
  1013.       If you only have to do this once, you    can do this:
  1014.  
  1015.           for $fh (FH1, FH2, FH3) {    print $fh "whatever\n" }
  1016.  
  1017.       To connect up    to one filehandle to several output
  1018.       filehandles, it's easiest to use the _t_e_e(1) program if you
  1019.       have it, and let it take care    of the multiplexing:
  1020.  
  1021.           open (FH,    "| tee file1 file2 file3");
  1022.  
  1023.       Or even:
  1024.  
  1025.           #    make STDOUT go to three    files, plus original STDOUT
  1026.           open (STDOUT, "| tee file1 file2 file3") or die "Teeing off: $!\n";
  1027.           print "whatever\n"               or die "Writing:    $!\n";
  1028.           close(STDOUT)                   or die "Closing:    $!\n";
  1029.  
  1030.       Otherwise you'll have    to write your own multiplexing print
  1031.       function -- or your own tee program -- or use    Tom
  1032.       Christiansen's, at
  1033.       http://www.perl.com/CPAN/authors/id/TOMC/scripts/tct.gz,
  1034.       which    is written in Perl and offers much greater
  1035.       functionality    than the stock version.
  1036.  
  1037.       HHHHoooowwww ccccaaaannnn IIII rrrreeeeaaaadddd iiiinnnn aaaa ffffiiiilllleeee bbbbyyyy ppppaaaarrrraaaaggggrrrraaaapppphhhhssss????
  1038.  
  1039.       Use the $\ variable (see the _p_e_r_l_v_a_r manpage for details).
  1040.       You can either set it    to "" to eliminate empty paragraphs
  1041.       ("abc\n\n\n\ndef", for instance, gets    treated    as two
  1042.       paragraphs and not three), or    "\n\n" to accept empty
  1043.       paragraphs.
  1044.  
  1045.       HHHHoooowwww ccccaaaannnn IIII rrrreeeeaaaadddd aaaa ssssiiiinnnngggglllleeee cccchhhhaaaarrrraaaacccctttteeeerrrr ffffrrrroooommmm aaaa ffffiiiilllleeee????  FFFFrrrroooommmm tttthhhheeee
  1046.       kkkkeeeeyyyybbbbooooaaaarrrrdddd????
  1047.  
  1048.       You can use the builtin getc() function for most
  1049.       filehandles, but it won't (easily) work on a terminal
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1061.  
  1062.  
  1063.  
  1064.       device.  For STDIN, either use the Term::ReadKey module from
  1065.       CPAN,    or use the sample code in the getc entry in the
  1066.       _p_e_r_l_f_u_n_c manpage.
  1067.  
  1068.       If your system supports POSIX, you can use the following
  1069.       code,    which you'll note turns    off echo processing as well.
  1070.  
  1071.           #!/usr/bin/perl -w
  1072.           use strict;
  1073.           $| = 1;
  1074.           for (1..4) {
  1075.           my $got;
  1076.           print    "gimme:    ";
  1077.           $got = getone();
  1078.           print    "--> $got\n";
  1079.           }
  1080.           exit;
  1081.  
  1082.           BEGIN {
  1083.           use POSIX qw(:termios_h);
  1084.  
  1085.           my ($term, $oterm, $echo, $noecho, $fd_stdin);
  1086.  
  1087.           $fd_stdin = fileno(STDIN);
  1088.  
  1089.           $term        = POSIX::Termios->new();
  1090.           $term->getattr($fd_stdin);
  1091.           $oterm     = $term->getlflag();
  1092.  
  1093.           $echo        = ECHO | ECHOK | ICANON;
  1094.           $noecho   = $oterm & ~$echo;
  1095.  
  1096.           sub cbreak {
  1097.               $term->setlflag($noecho);
  1098.               $term->setcc(VTIME, 1);
  1099.               $term->setattr($fd_stdin,    TCSANOW);
  1100.           }
  1101.  
  1102.           sub cooked {
  1103.               $term->setlflag($oterm);
  1104.               $term->setcc(VTIME, 0);
  1105.               $term->setattr($fd_stdin,    TCSANOW);
  1106.           }
  1107.  
  1108.           sub getone {
  1109.               my $key =    '';
  1110.               cbreak();
  1111.               sysread(STDIN, $key, 1);
  1112.               cooked();
  1113.               return $key;
  1114.           }
  1115.  
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1127.  
  1128.  
  1129.  
  1130.           }
  1131.  
  1132.           END { cooked() }
  1133.  
  1134.       The Term::ReadKey module from    CPAN may be easier to use:
  1135.  
  1136.           use Term::ReadKey;
  1137.           open(TTY,    "</dev/tty");
  1138.           print "Gimme a char: ";
  1139.           ReadMode "raw";
  1140.           $key = ReadKey 0,    *TTY;
  1141.           ReadMode "normal";
  1142.           printf "\nYou said %s, char number %03d\n",
  1143.           $key,    ord $key;
  1144.  
  1145.       For DOS systems, Dan Carson <dbc@tc.fluke.COM> reports the
  1146.       following:
  1147.  
  1148.       To put the PC    in "raw" mode, use ioctl with some magic
  1149.       numbers gleaned from msdos.c (Perl source file) and Ralf
  1150.       Brown's interrupt list (comes    across the net every so
  1151.       often):
  1152.  
  1153.           $old_ioctl = ioctl(STDIN,0,0);     # Gets    device info
  1154.           $old_ioctl &= 0xff;
  1155.           ioctl(STDIN,1,$old_ioctl | 32);     # Writes it back, setting bit 5
  1156.  
  1157.       Then to read a single    character:
  1158.  
  1159.           sysread(STDIN,$c,1);         # Read    a single character
  1160.  
  1161.       And to put the PC back to "cooked" mode:
  1162.  
  1163.           ioctl(STDIN,1,$old_ioctl);     # Sets    it back    to cooked mode.
  1164.  
  1165.       So now you have $c.  If ord($c) == 0,    you have a two byte
  1166.       code,    which means you    hit a special key.  Read another byte
  1167.       with sysread(STDIN,$c,1), and    that value tells you what
  1168.       combination it was according to this table:
  1169.  
  1170.           #    PC 2-byte keycodes = ^@    + the following:
  1171.  
  1172.  
  1173.  
  1174.  
  1175.  
  1176.  
  1177.  
  1178.  
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1193.  
  1194.  
  1195.  
  1196.           #    HEX    KEYS
  1197.           #    ---    ----
  1198.           #    0F    SHF TAB
  1199.           #    10-19    ALT QWERTYUIOP
  1200.           #    1E-26    ALT ASDFGHJKL
  1201.           #    2C-32    ALT ZXCVBNM
  1202.           #    3B-44    F1-F10
  1203.           #    47-49    HOME,UP,PgUp
  1204.           #    4B    LEFT
  1205.           #    4D    RIGHT
  1206.           #    4F-53    END,DOWN,PgDn,Ins,Del
  1207.           #    54-5D    SHF F1-F10
  1208.           #    5E-67    CTR F1-F10
  1209.           #    68-71    ALT F1-F10
  1210.           #    73-77    CTR LEFT,RIGHT,END,PgDn,HOME
  1211.           #    78-83    ALT 1234567890-=
  1212.           #    84    CTR PgUp
  1213.  
  1214.       This is all trial and    error I    did a long time    ago, I hope
  1215.       I'm reading the file that worked.
  1216.  
  1217.       HHHHoooowwww ccccaaaannnn IIII tttteeeellllllll iiiiffff tttthhhheeeerrrreeee''''ssss aaaa cccchhhhaaaarrrraaaacccctttteeeerrrr    wwwwaaaaiiiittttiiiinnnngggg    oooonnnn aaaa
  1218.       ffffiiiilllleeeehhhhaaaannnnddddlllleeee????
  1219.  
  1220.       The very first thing you should do is    look into getting the
  1221.       Term::ReadKey    extension from CPAN.  It now even has limited
  1222.       support for closed, proprietary (read: not open systems, not
  1223.       POSIX, not Unix, etc)    systems.
  1224.  
  1225.       You should also check    out the    Frequently Asked Questions
  1226.       list in comp.unix.* for things like this: the    answer is
  1227.       essentially the same.     It's very system dependent.  Here's
  1228.       one solution that works on BSD systems:
  1229.  
  1230.           sub key_ready {
  1231.           my($rin, $nfd);
  1232.           vec($rin, fileno(STDIN), 1) =    1;
  1233.           return $nfd =    select($rin,undef,undef,0);
  1234.           }
  1235.  
  1236.       If you want to find out how many characters are waiting,
  1237.       there's also the FIONREAD ioctl call to be looked at.
  1238.  
  1239.       The _h_2_p_h tool    that comes with    Perl tries to convert C
  1240.       include files    to Perl    code, which can    be required.  FIONREAD
  1241.       ends up defined as a function    in the _s_y_s/_i_o_c_t_l._p_h file:
  1242.  
  1243.           require 'sys/ioctl.ph';
  1244.  
  1245.           $size = pack("L",    0);
  1246.           ioctl(FH,    FIONREAD(), $size)    or die "Couldn't call ioctl: $!\n";
  1247.           $size = unpack("L", $size);
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1259.  
  1260.  
  1261.  
  1262.       If _h_2_p_h wasn't installed or doesn't work for you, you    can
  1263.       _g_r_e_p the include files by hand:
  1264.  
  1265.           %    grep FIONREAD /usr/include/*/*
  1266.           /usr/include/asm/ioctls.h:#define    FIONREAD      0x541B
  1267.  
  1268.       Or write a small C program using the editor of champions:
  1269.  
  1270.           %    cat > fionread.c
  1271.           #include <sys/ioctl.h>
  1272.           main() {
  1273.           printf("%#08x\n", FIONREAD);
  1274.           }
  1275.           ^D
  1276.           %    cc -o fionread fionread
  1277.           %    ./fionread
  1278.           0x4004667f
  1279.  
  1280.       And then hard-code it, leaving porting as an exercise    to
  1281.       your successor.
  1282.  
  1283.           $FIONREAD    = 0x4004667f;          #    XXX: opsys dependent
  1284.  
  1285.           $size = pack("L",    0);
  1286.           ioctl(FH,    $FIONREAD, $size)     or die "Couldn't call ioctl: $!\n";
  1287.           $size = unpack("L", $size);
  1288.  
  1289.       FIONREAD requires a filehandle connected to a    stream,
  1290.       meaning sockets, pipes, and tty devices work,    but _n_o_t    files.
  1291.  
  1292.       HHHHoooowwww ddddoooo IIII ddddoooo aaaa    ttttaaaaiiiillll ----ffff    in perl?
  1293.  
  1294.       First    try
  1295.  
  1296.           seek(GWFILE, 0, 1);
  1297.  
  1298.       The statement    seek(GWFILE, 0,    1) doesn't change the current
  1299.       position, but    it does    clear the end-of-file condition    on the
  1300.       handle, so that the next <GWFILE> makes Perl try again to
  1301.       read something.
  1302.  
  1303.       If that doesn't work (it relies on features of your stdio
  1304.       implementation), then    you need something more    like this:
  1305.  
  1306.           for (;;) {
  1307.             for    ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE)) {
  1308.               #    search for some    stuff and put it into files
  1309.             }
  1310.             # sleep for    a while
  1311.             seek(GWFILE, $curpos, 0);  # seek to where we had been
  1312.           }
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1325.  
  1326.  
  1327.  
  1328.       If this still    doesn't    work, look into    the POSIX module.
  1329.       POSIX    defines    the _c_l_e_a_r_e_r_r() method, which can remove    the
  1330.       end of file condition    on a filehandle.  The method: read
  1331.       until    end of file, _c_l_e_a_r_e_r_r(), read some more.  Lather,
  1332.       rinse, repeat.
  1333.  
  1334.       HHHHoooowwww ddddoooo IIII _d_u_p() a filehandle in Perl?
  1335.  
  1336.       If you check the open    entry in the _p_e_r_l_f_u_n_c manpage, you'll
  1337.       see that several of the ways to call _o_p_e_n() should do    the
  1338.       trick.  For example:
  1339.  
  1340.           open(LOG,    ">>/tmp/logfile");
  1341.           open(STDERR, ">&LOG");
  1342.  
  1343.       Or even with a literal numeric descriptor:
  1344.  
  1345.          $fd = $ENV{MHCONTEXTFD};
  1346.          open(MHCONTEXT, "<&=$fd");      # like fdopen(3S)
  1347.  
  1348.       Note that "<&STDIN" makes a copy, but    "<&=STDIN" make    an
  1349.       alias.  That means if    you close an aliased handle, all
  1350.       aliases become inaccessible.    This is    not true with a    copied
  1351.       one.
  1352.  
  1353.       Error    checking, as always, has been left as an exercise for
  1354.       the reader.
  1355.  
  1356.       HHHHoooowwww ddddoooo IIII cccclllloooosssseeee aaaa ffffiiiilllleeee    ddddeeeessssccccrrrriiiippppttttoooorrrr bbbbyyyy nnnnuuuummmmbbbbeeeerrrr????
  1357.  
  1358.       This should rarely be    necessary, as the Perl _c_l_o_s_e()
  1359.       function is to be used for things that Perl opened itself,
  1360.       even if it was a dup of a numeric descriptor,    as with
  1361.       MHCONTEXT above.  But    if you really have to, you may be able
  1362.       to do    this:
  1363.  
  1364.           require 'sys/syscall.ph';
  1365.           $rc = syscall(&SYS_close,    $fd + 0);  # must force    numeric
  1366.           die "can't sysclose $fd: $!" unless $rc == -1;
  1367.  
  1368.  
  1369.       WWWWhhhhyyyy ccccaaaannnn''''tttt IIII uuuusssseeee """"CCCC::::\\\\tttteeeemmmmpppp\\\\ffffoooooooo""""    iiiinnnn DDDDOOOOSSSS ppppaaaatttthhhhssss????  WWWWhhhhaaaatttt ddddooooeeeessssnnnn''''tttt
  1370.       ````CCCC::::\\\\tttteeeemmmmpppp\\\\ffffoooooooo....eeeexxxxeeee```` wwwwoooorrrrkkkk????
  1371.  
  1372.       Whoops!  You just put    a tab and a formfeed into that
  1373.       filename!  Remember that within double quoted    strings
  1374.       ("like\this"), the backslash is an escape character.    The
  1375.       full list of these is    in the section on _Q_u_o_t_e    _a_n_d _Q_u_o_t_e-_l_i_k_e
  1376.       _O_p_e_r_a_t_o_r_s in the _p_e_r_l_o_p manpage.  Unsurprisingly, you    don't
  1377.       have a file called "_c:(tab)_e_m_p(formfeed)oo" or
  1378.       "_c:(tab)_e_m_p(formfeed)oo.exe" on your DOS filesystem.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1391.  
  1392.  
  1393.  
  1394.       Either single-quote your strings, or (preferably) use
  1395.       forward slashes.  Since all DOS and Windows versions since
  1396.       something like MS-DOS    2.0 or so have treated / and \ the
  1397.       same in a path, you might as well use    the one    that doesn't
  1398.       clash    with Perl -- or    the POSIX shell, ANSI C    and C++, awk,
  1399.       Tcl, Java, or    Python,    just to    mention    a few.
  1400.  
  1401.       WWWWhhhhyyyy ddddooooeeeessssnnnn''''tttt _g_l_o_b("*.*") get all the files?
  1402.  
  1403.       Because even on non-Unix ports, Perl's glob function follows
  1404.       standard Unix    globbing semantics.  You'll need glob("*") to
  1405.       get all (non-hidden) files.  This makes _g_l_o_b() portable.
  1406.  
  1407.       WWWWhhhhyyyy ddddooooeeeessss PPPPeeeerrrrllll    lllleeeetttt mmmmeeee ddddeeeelllleeeetttteeee rrrreeeeaaaadddd----oooonnnnllllyyyy    ffffiiiilllleeeessss????    WWWWhhhhyyyy ddddooooeeeessss ----iiii
  1408.       clobber protected files?  Isn't this a bug in    Perl?
  1409.  
  1410.       This is elaborately and painstakingly    described in the "Far
  1411.       More Than You    Ever Wanted To Know" in
  1412.       http://www.perl.com/CPAN/doc/FMTEYEWTK/file-dir-perms    .
  1413.  
  1414.       The executive    summary: learn how your    filesystem works.  The
  1415.       permissions on a file    say what can happen to the data    in
  1416.       that file.  The permissions on a directory say what can
  1417.       happen to the    list of    files in that directory.  If you
  1418.       delete a file, you're    removing its name from the directory
  1419.       (so the operation depends on the permissions of the
  1420.       directory, not of the    file).    If you try to write to the
  1421.       file,    the permissions    of the file govern whether you're
  1422.       allowed to.
  1423.  
  1424.       HHHHoooowwww ddddoooo IIII sssseeeelllleeeecccctttt aaaa rrrraaaannnnddddoooommmm lllliiiinnnneeee    ffffrrrroooommmm aaaa ffffiiiilllleeee????
  1425.  
  1426.       Here's an algorithm from the Camel Book:
  1427.  
  1428.           srand;
  1429.           rand($.) < 1 && ($line = $_) while <>;
  1430.  
  1431.       This has a significant advantage in space over reading the
  1432.       whole    file in.  A simple proof by induction is available
  1433.       upon request if you doubt its    correctness.
  1434.  
  1435.      AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD    CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1436.       Copyright (c)    1997, 1998 Tom Christiansen and    Nathan
  1437.       Torkington.  All rights reserved.
  1438.  
  1439.       When included    as an integrated part of the Standard
  1440.       Distribution of Perl or of its documentation (printed    or
  1441.       otherwise), this works is covered under Perl's Artistic
  1442.       Licence.  For    separate distributions of all or part of this
  1443.       FAQ outside of that, see the _p_e_r_l_f_a_q manpage.
  1444.  
  1445.       Irrespective of its distribution, all    code examples here are
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ5555((((1111))))
  1457.  
  1458.  
  1459.  
  1460.       public domain.  You are permitted and    encouraged to use this
  1461.       code and any derivatives thereof in your own programs    for
  1462.       fun or for profit as you see fit.  A simple comment in the
  1463.       code giving credit to    the FAQ    would be courteous but is not
  1464.       required.
  1465.  
  1466.  
  1467.  
  1468.  
  1469.  
  1470.  
  1471.  
  1472.  
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.  
  1480.  
  1481.  
  1482.  
  1483.  
  1484.  
  1485.  
  1486.  
  1487.  
  1488.  
  1489.  
  1490.  
  1491.  
  1492.  
  1493.  
  1494.  
  1495.  
  1496.  
  1497.  
  1498.  
  1499.  
  1500.  
  1501.  
  1502.  
  1503.  
  1504.  
  1505.  
  1506.  
  1507.  
  1508.  
  1509.  
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.